package com.metaverse.backend.web;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.metaverse.backend.dto.gen.GenCode;
import com.metaverse.backend.dto.gen.TableField;
import com.metaverse.backend.service.GenCodeService;
import com.metaverse.backend.utils.JsonUtils;
import com.metaverse.backend.utils.PinYinUtil;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.text.CaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/genCode")
public class GenCodeController {
    @Autowired
    private GenCodeService genCodeService;

    @GetMapping("/all")
    public List<GenCode> all(GenCode record) throws IOException {

        BufferedReader reader = null;

        List<GenCode> genCodeList = new ArrayList<>();

        String genJsonPath = Paths.get(System.getProperty("user.dir"), "src", "main", "resources", "genjson")
                .toString();

//            File file = ResourceUtils.getFile("classpath:genjson");
        File file = new File(genJsonPath);
        File[] fs = file.listFiles();    //遍历path下的文件和目录，放在File数组中
        if (fs != null) {
            for (File f : fs) {                    //遍历File[]数组
                if (!f.isDirectory()) {//若非目录(即文件)，则打印
                    System.out.println(f);
                    reader = new BufferedReader(new FileReader(f));
                    Gson gson = new GsonBuilder().create();

                    GenCode genCode = gson.fromJson(reader, GenCode.class);
                    genCodeList.add(genCode);
                    reader.close();
                }
            }
        }

        return genCodeList;
    }

    @GetMapping("/getOne")
    public GenCode getGenCode(@RequestParam String className) throws IOException {
        File file = new File(Paths.get(System.getProperty("user.dir"), "src", "main", "resources", "genjson", className + ".json")
                .toString());

        BufferedReader reader = new BufferedReader(new FileReader(file));
        Gson gson = new Gson();

        GenCode genCode = gson.fromJson(reader, GenCode.class);

        reader.close();

        return genCode;
    }

    @PostMapping("/save")
    public GenCode save(@RequestBody GenCode record) {
        try {

            String basePackage = this.getClass().getPackage().getName().replace(".web", "");
            record.setBasePackage(basePackage);
            String genPackage = record.getTablePackage()
                    .replace(basePackage + ".domain.", "")
                    .replace("." + record.getTableName(), "");
            if (!genPackage.startsWith(record.getTableName())) {
                record.setGenPackage(genPackage);
            } else {
                record.setGenPackage(null);
            }

            Gson gson = new Gson();
            String genCodeStr = gson.toJson(record);
            String resourcesPath = record.getResourcesPath();
            String genCodeName = record.getClassName() + ".json";
            genCode(record);

            try {
                File dir = new File(resourcesPath + "/genjson/");
                dir.mkdirs();

                File file = new File(resourcesPath + "/genjson/" + genCodeName);
                file.createNewFile();

                BufferedWriter output = new BufferedWriter(new FileWriter(file));
                output.write(genCodeStr);
                output.close();

            } catch (Exception e) {
                System.err.println("获取文件列表失败！");
                e.printStackTrace();
            }

            return record;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void genCode(@RequestBody GenCode record) throws Exception {
        String tableName = record.getTableName();

        if (PinYinUtil.isContainChinese(tableName)) {
            tableName = PinYinUtil.getStringPinYin(tableName);
        }

        if (StringUtils.isEmpty(record.getClassName())) {
            record.setClassName(CaseUtils.toCamelCase(tableName, true, '_'));
        }
        if (Pattern.matches(".*[ _\\-].*", record.getClassName())) {
            record.setClassName(CaseUtils.toCamelCase(tableName, true, '_', ' ', '-'));
        }
        record.setClassName(StringUtils.capitalize(record.getClassName()));


        //GeneratorTool.getImports(record);


        if (record.getGenClass()) {
            genCodeService.genController(record);
            genCodeService.genService(record);
            genCodeService.genRepo(record);
        }
        if (record.getGenList()) {
            genCodeService.genListView(record);
        }
        if (record.getGenForm()) {
            genCodeService.genEditView(record);
        }
        if (record.getGenRouter()) {
            genCodeService.genRouter(record);
        }

        Process process = new ProcessBuilder()
                .command("npm", "run", "lint")
                .directory(Paths.get(record.getRouterPath()).getParent().toFile())
                .start();
        process.waitFor();
    }

    //
//    /**
//     * <p>删除。</p>
//     */
//    @RequestMapping(value = "/del", method = RequestMethod.POST)
//    @ResponseBody
//    public Result deleteGenCode(@RequestParam(required = true, value = "id") String id) {
//
//        boolean num = genCodeService.deleteGenCode(id);
//        if (num) {
//            return new Result(true, "删除成功");
//        }
//        return new Result(false, "删除异常");
//    }
//
    @GetMapping("/getSrcPath")
    public Map<String, Object> getSrcPath() {
        Map<String, Object> map = new HashMap<>();
        List<String> javaPath = new ArrayList<>(Arrays.asList("src", "main", "java"));
        javaPath.addAll(Arrays.asList(this.getClass().getPackage().getName().split("\\.")));
        map.put("javaPath", Paths.get(System.getProperty("user.dir"),
                javaPath.toArray(new String[0])).getParent().toString());
        map.put("viewPath", Paths.get(System.getProperty("user.dir"), "src", "main", "vue", "src", "views").toString());
        map.put("routerPath", Paths.get(System.getProperty("user.dir"), "src", "main", "vue", "src").toString());
        map.put("resourcesPath", Paths.get(System.getProperty("user.dir"), "src", "main", "resources").toString());
        return map;
    }
//
//    @RequestMapping(value = "/tables", method = RequestMethod.GET)
//    @ResponseBody
//    public Result tables(DataSourceInfo dataSourceInfo) {
//
//        if (StringUtils.isNotEmpty(dataSourceInfo.getCode()) && !"dataSource".equals(dataSourceInfo.getCode())) {
//            dataSourceInfo = dataSourceInfoService.getDataSourceInfo(dataSourceInfo);
//            if (dataSourceInfo != null) {
//
//                List<String> pp = DatabaseUtil.loadDatabaseTables(dataSourceInfo);
//                return new Result(true, pp);
//            }
//        } else {
//            List<String> pp = DatabaseUtil.loadDatabaseTables(dataSourceInfo);
//            return new Result(true, pp);
//        }
//
//
//        return new Result(false, "获取失败");
//    }
//

    @GetMapping("/tableFields")
    public List<TableField> tableFields(@RequestParam String className) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        List<TableField> tableFieldList = new ArrayList<>();
        for (Field declaredField : Class.forName(className).getDeclaredFields()) {
            JsonIgnore jsonIgnore = declaredField.getDeclaredAnnotation(JsonIgnore.class);
            if (jsonIgnore != null) {
                continue;
            }
            TableField tableField = new TableField();
            tableField.setName(declaredField.getName());
            tableField.setModelName(declaredField.getName());
            tableField.setRemark(declaredField.getName());
            tableField.setShowInList(true);
            tableField.setShowInForm(true);
            if (declaredField.getType().isEnum()) {
                tableField.setFormType("select");
                tableField.setApiFlag("1");
                JsonUtils.ArrayBuilder builder = new JsonUtils.ArrayBuilder();
                for (Object enumConstant : declaredField.getType().getEnumConstants()) {
                    String name = (String) enumConstant.getClass().getMethod("name").invoke(enumConstant);
                    String desc = name;
                    try {
                        desc = (String) enumConstant.getClass().getMethod("getDescription").invoke(enumConstant);
                    } catch (NoSuchMethodException ignore) {
                    }
                    Map<String, String> map = new HashMap<>();
                    map.put("label", desc);
                    map.put("value", name);
                    builder.add(map);
                }
                tableField.setOptionsValue(builder.build());
            } else {
                switch (declaredField.getType().getName()) {
                    case "java.lang.Boolean":
                        tableField.setFormType("switch");
                        break;
                    case "java.lang.Integer":
                    case "java.lang.Long":
                    case "java.lang.Double":
                    case "java.lang.Float":
                    case "java.math.BigDecimal":
                        tableField.setFormType("number");
                        break;
                    case "java.time.LocalDateTime":
                    case "java.util.Date":
                        tableField.setFormType("datetime");
                        break;
                    case "java.time.LocalDate":
                        tableField.setFormType("date");
                        break;
                    default:
                        tableField.setFormType("singleLineText");
                }
            }
            ApiModelProperty apiModelProperty = declaredField.getDeclaredAnnotation(ApiModelProperty.class);
            if (apiModelProperty != null) {
                tableField.setRemark(apiModelProperty.value());
            }
            tableFieldList.add(tableField);
        }
        return tableFieldList;
    }
}

